package com.jwcao.common.cast.operation.access.field.collection;

import com.jwcao.common.cast.context.CastContext;
import com.jwcao.common.cast.annotation.CastField;
import com.jwcao.common.cast.operation.CastFlow;
import com.jwcao.common.cast.operation.access.field.CastFieldAccessOperation;
import com.jwcao.common.scan.object.ScanField;
import java.util.Map;

/**
 * name: CollectionFieldAccessOperation description: TODO
 *
 * @author caojingwei date: 2023/3/24 14:14
 */
public class ListFieldAccessOperation extends CastFieldAccessOperation {

    protected final Class sourceItemClass;

    protected final Class targetItemClass;

    public ListFieldAccessOperation(CastField castField, ScanField sourceField,
        ScanField targetField, Class sourceItemClass, Class targetItemClass) {
        super(castField, sourceField, targetField);
        this.sourceItemClass = sourceItemClass;
        this.targetItemClass = targetItemClass;
    }

    @Override
    public CastFieldAccessOperation flush() {
        // 如果一样不用处理
        if (sourceItemClass == targetItemClass) {
            return this;
        }

        //1. sourceField 是泛型
        if (sourceField.isAbstractOrInterface()) {
            Map<Class, CastFlow> castFlowMap = CastContext.getCastFlowMapBySubClass(sourceItemClass, targetItemClass,
                fieldCastId);
            return new GenericsListAccessOperation(castField, sourceField, targetField, sourceItemClass,
                targetItemClass,
                castFlowMap);
        }

        //2. 如果是明确类型
        CastFlow castFlow = CastContext.getCastFlowByClass(sourceItemClass, targetItemClass, fieldCastId);
        return new RecursionListAccessOperation(castField, sourceField, targetField, sourceItemClass, targetItemClass,
            castFlow);
    }
}
